<!-- TOPBAR S -->
<header class="top-bar flex-row">
  <span class="row-item row-item-auto top-bar-back" onclick="window.history.back()">返回</span>
  <h3 class="row-item top-bar-name">{$productGoods.name}</h3>
</header>
<!-- TOPBAR E -->

<!-- 商品信息描述 S -->
<figure class="product-img">
  <img class="w100" src="{$productGoods.pic}" alt="{$productGoods.name}">
</figure>

<section class="product-price flex-row">

  <div class="row-item">
    <del class="product-original-price">{$productGoods.price_high}</del>
    <strong class="stress product-now-price">{$productGoods['is_low']?$productGoods['price_low']:$productGoods['price']}</strong>
  </div>

  <div class="row-item">
    <p><strong class="icon icon-product-money">￥</strong>节省<span class="stress stress-product-money">{$productGoods['price_high']-($productGoods['is_low']?$productGoods['price_low']:$productGoods['price'])}元</span></p>
    <p><strong class="icon icon-product-person">人</strong><span class="stress stress-product-person">{$productGoods[saled_base]+$productGoods[saled_count]}</span>人购买</p>
  </div>

</section>
<!-- 商品信息描述 E -->

<!-- 商品类型以及数量的选择  -->
<form id="form" method="post" action="{:U('ShopOrder/confirmOrder')}">
  
  <section id="product-buy-check" class="product-item pd10 product-buy-check">
    
    <!-- 类型 -->
    <volist name="productGoods.attributes" id="vo">
    <dl class="clearfix buy-check">
      <dt class="key">{$vo.name}：</dt>
      <dd class="value">
        <foreach name="vo.values" key="key" item="item">
        <input type="radio" id="{$vo.id}|{$key}" name="attrs[{$vo.id}]" value="{$key}">
        <label class="check-item" data-value="{$vo.id}|{$key}" for="{$vo.id}|{$key}">{$item}</label>
        </foreach>
      </dd>
    </dl>
    </volist>
    
    <!-- 购买数量 -->
    <dl class="clearfix">
      <dt class="key">数量：</dt>
      <dd class="value">
        <span class="product-number">
          <span class="buy-num-minus" id="buy-num-minus">-</span>
          <input class="buy-num" id="buy-num" name="quantity" readonly="readonly" value="1">
          <span class="buy-num-plus" id="buy-num-plus">+</span>
        </span>
      </dd>
    </dl>
    
  </section>
  
  <section class="product-item product-buy">
    <button class="buy-btn cart" id="cart">加入购物车</button>
    <input type="hidden" name="id" value="{$productGoods.id}">
    <input type="hidden" name="sid" value="{$sid}">
    <button type="submit" class="buy-btn buy" id="buy">立即购买</button>
  </section>
  
</form>


<!-- 商品详情以及评价 S -->
<section class="product-item product-detail">
  <header id="product-tab">
    <a href="javascript:;" class="current" data-id="product-content">商品详情</a>
    <a href="javascript:;" data-id="product-comment">商品评价</a>
  </header>
  <div class="wrap pd10" id="product-content">{$productGoods.content}</div>
  <div class="wrap pd10" id="product-comment"></div>
</section>
<!-- 商品详情以及评价 E -->

<!-- 其他用户还买的商品 S -->
<section class="product-item list-block">
  <h3 class="list-block-title">大家还买了</h3>
  <ul class="flex-row other-buy">
    <tag:shopAlsoBought id="vo" product_id="$productGoods['id']" limit="3">
    <li class="row-item">
      <a href="{$vo.url}">
        <img src="{$vo.pic}" alt="">
        <p>{$vo.name}</p>
        <p class="stress">{$vo.price}</p>
      </a>
    </li>
    </tag:shopAlsoBought>
  </ul>
</section>
<!-- 其他用户还买的商品 E -->

<script type="text/javascript">
  (function(){
    
    // 属性选择点击
    var radios = document.querySelectorAll ( "#product-buy-check input[type=radio]" );
    [].forEach.call ( radios, function( item ) {
      item.addEventListener ( "change", buyCheckAttr, false );
    });
    
    function nextElement ( node ) {
      if ( node.nextSibling.nodeType === 1 ) {
        return node.nextSibling;
      } else if ( node.nextSibling.nodeType === 3 ) {
        return nextElement( node.nextSibling );
      };
    };
    
    // 属性选择和样式转换
    function buyCheckAttr () {
      var reg = new RegExp ( /(^| )checked( |$)/ ),
          checklabels = this.parentNode.querySelectorAll( "label" ) ;
      // 单选，将所有同级元素的 class 去除选中状态
      [].forEach.call( checklabels, function( item ) {
        item.classList.remove( "checked" );
      });
      nextElement( this ).classList.add( "checked" );
    };

    // 购买数量的增减
    var buyMinus = document.getElementById( "buy-num-minus" ),
        buyNum = document.getElementById( "buy-num" ),
        buyPlus = document.getElementById( "buy-num-plus" );
    buyMinus.addEventListener( "click", function() {
      changeNumber( false );
    }, false );
    buyPlus.addEventListener( "click", function() {
      changeNumber( true );
    }, false );

    function changeNumber( plus ) {
      var v = parseInt( buyNum.value );
      if ( plus ) {
        buyNum.value = v + 1;
      } else {
        ( v <= 1 ) || ( buyNum.value = v - 1 );
      };
    };

    // 加入购物车，购买
    var oCart = document.getElementById( "cart" ),
        oBuy = document.getElementById( "buy" ),
        oForm = document.getElementById("form"),
        checkData = "",
        buyNum = document.getElementById( "buy-num" );
    oCart.addEventListener( "click", insertCart, false );
    oBuy.addEventListener( "click", buyNow, false );
    oCartCount = document.getElementById( "cartCount" );

    // 加入购物车
    function insertCart() {
      oForm.onsubmit = function( event ){ event.preventDefault(); }
      checkData = "";
      if ( checkAttr() ) {
        var data = {};
        data.attrs = checkData.replace( /,$/, "" );
        data.quantity = buyNum.value;
        data.sid = {$sid};
        data.id = {$productGoods.id};
        // ajax请求加入购物车
        GH.ajax( "{:U('ShopCart/addItem')}", data, function(data){
          GH.showMessage( data.msg );
          // oCartCount.innerHTML = parseInt(oCartCount.innerHTML) + parseInt(buyNum.value);
        },"post" )
      }
    };

    // 立即购买
    function buyNow() {
      if ( checkAttr() ) {
        oForm.submit();
      } else {
        oForm.onsubmit = function( event ){ event.preventDefault(); }
      }
    };
    
    // 检查是否已经选择所有属性
    function checkAttr() {
      var buyCheck = document.querySelectorAll( "#product-buy-check .buy-check" ),
          checkAll = true,
          i = 0,
          item = null;

      for (i; item = buyCheck[i]; i++) {
        
        var radio = item.querySelectorAll( "input[type=radio]" ),
            j = 0,
            radioCheck = false,
            radioItem = null;
            
        // 判断单选框是否有被选中
        for (j; radioItem = radio[j]; j++) {
          radioItem.checked && ( radioCheck = true );
        };
        
        if ( !radioCheck ) {
          att = item.querySelector(".key").innerHTML.replace("：","");
          GH.showMessage( "请选择" + att );
          checkAll = false;
          checkDate = "";
          return false;
        } else {
          checkData += ( item.querySelector(".checked").getAttribute("data-value") + "," );  
        };
      };

      return checkAll;
    };
    
    // 获取商品评价内容
    var productId = {$productGoods.id};
    GH.ajax( "{:U('Home/Rate/moreRate')}", { "product_id": productId }, function( data ) {
      data.extra && ( showComment( data.extra ) );
    });
    
    function showComment( data ) {
      var html = "";
      for (var i = 0; item = data[i]; i++) {
        html += "<li><p>" + item.content + "</p>"
               +"<div class='user clearfix'><span>" + item.userNickName + "</span><time>" + new Date(item.create_time*1000).Format("yyyy-MM-dd hh:mm:ss") + "</time></div>"
               +"</li>";
      };
      document.getElementById( "product-comment" ).innerHTML = "<ul class='product-comment'>" + html + "</ul>";
    };
    
    Date.prototype.Format = function(fmt) { 
      var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
      }; 
      if(/(y+)/.test(fmt)) 
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
      for(var k in o) 
        if(new RegExp("("+ k +")").test(fmt)) 
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
      return fmt; 
    };
    
    // 切换商品详情和评价
    var productTab = document.querySelectorAll( "#product-tab a" );
    [].forEach.call( productTab, function( obj ) {
      obj.addEventListener("click", clickTab, false);
    });

    // 切换Tab
    function clickTab() {
      [].forEach.call(productTab, function( obj ) {
        obj.className = "";
        document.getElementById( obj.getAttribute("data-id") ).style.display = "none";
      });
      this.className = "current";
      document.getElementById( this.getAttribute("data-id") ).style.display = "block";
    };
  })();
</script>